package com.redoor.app.stake.basicdata.mq.consumerService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.redoor.app.stake.auth.commons.DatabaseServiceStatus;
import com.redoor.app.stake.basicdata.model.*;
import com.redoor.app.stake.basicdata.service.*;
import com.redoor.app.stake.common.utils.UUIDTool;
import com.yotouch.app.stake.StakeConsts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sunbox.core.hsf.api.StakeService;
import sunbox.core.hsf.vo.ModelRuleItem;
import sunbox.core.vo.api.OpenAPIResponse;

import java.util.Date;
import java.util.List;

/**
 * Created by zhangYiHang on 2018/4/10.
 */
@Service
public class UpdateModelMessageListener implements MessageListener {

    private static final Logger logger = LoggerFactory.getLogger(UpdateModelMessageListener.class) ;

    @Autowired
    StakeService stakeService;
    //电费模型
    @Autowired
    private SyncChargerFeeModelService syncChargerFeeModelService;
    //服务费模型
    @Autowired
    private SyncServiceFeeModelService syncServiceFeeModelService;
    //充电桩
    @Autowired
    private BaseStakeService baseStakeService;
    //计费模型关系表
    @Autowired
    private BaseFeeModelRelService baseFeeModelRelService;
    @Autowired
    LogService logService;

    /**
     * 监听处理程序
     *
     * @param message
     * @param context
     * @return
     */
    @Override
    public Action consume(Message message, ConsumeContext context) {

        // modelId
        String str = new String(message.getBody());
        logger.info("UpdateModelMessageListener_consume_MQListener_MessageBody_of_FeeModel:"+str);
        JSONObject jsonObject = JSONObject.parseObject(str);
        String stakeNo = jsonObject.getString("stakeNo");
        
        /*mq日志记录*/
        BaseMqOperationLog baseMqOperationLog = new BaseMqOperationLog();
        baseMqOperationLog.setUuid(UUIDTool.getUUID());
        baseMqOperationLog.setMessagetopic(message.getTopic());
        baseMqOperationLog.setMessagebody(message.getBody().toString());
        baseMqOperationLog.setMessagetag(message.getTag());
        baseMqOperationLog.setType(2);
        boolean canSaveMqLog = false;

        /*调用接口*/
        OpenAPIResponse r = stakeService.requestModel(null, null, null, stakeNo) ;
        List<ModelRuleItem> modelRuleItems = (List<ModelRuleItem>)r.getData() ;

        logger.info("UpdateModelMessageListener_consume_Num_of_FeeModel_got_from_MQListener:"+modelRuleItems.size());
        if(modelRuleItems != null && modelRuleItems.size() > 0){
            for(ModelRuleItem item : modelRuleItems){
                logger.info("UpdateModelMessageListener_consume_oneOf_MQListener_MessageBody_of_FeeModel:"+JSONObject.toJSONString(item));
                if(0 < saveModel(item,stakeNo)){
                    canSaveMqLog = true;
                }
            }
        }

        /*如果该mq消息的接收修改了数据库内容,则保存mq日志到redis*/
        if (canSaveMqLog){
            logService.addLogToRedis(baseMqOperationLog, LogEnum.MQ_LOG);
        }

        return Action.CommitMessage ;
    }

    /**
     * 计费模型新增处理
     * @param item
     * @param stakeNo
     */
    private int saveModel(ModelRuleItem item,String stakeNo) {
        int result = 0;
        String type = item.getServerType();
        String modelId = item.getModelId();
        Date date = item.getExpireDate();
        //01  电费模型
        if(StakeConsts.FEE_MODEL_TYPE_CHARGER.equals(type)){
            SyncChargerFeeModel syncChargerFeeModel = this.syncChargerFeeModelService.qryChargerFeeModelById(modelId);
            if(syncChargerFeeModel != null){
                logger.info("UpdateModelMessageListener_saveModel_FeeModel_exist:"+JSONObject.toJSONString(item));
            }else {
                if(date != null){
                    syncChargerFeeModel.setUneeffectiveat(date);
                }
                //第一档冻结资金
                syncChargerFeeModel.setFirstlevelfrozenmoney(item.getFirstPrice().intValueExact());
                //第二档冻结资金
                syncChargerFeeModel.setSecondlevelfrozenmoney(item.getSecondPrice().intValueExact());
                //id
                syncChargerFeeModel.setId(modelId);
                syncChargerFeeModel.setEffectiveat( item.getEffectDate());
                //尖峰费率之尖峰率
                syncChargerFeeModel.setSharpfee( item.getPriceSpot());
                //尖峰费率之峰费率
                syncChargerFeeModel.setOvershootfee(item.getPricePeak());
                //平谷费率之平费率
                syncChargerFeeModel.setFlatfee(item.getPricePeace());
                //平谷费率之谷费率
                syncChargerFeeModel.setValleyfee(item.getPriceVally());
                //模型名称
                syncChargerFeeModel.setName(item.getModelName());
                syncChargerFeeModel.setStatus(Integer.valueOf(DatabaseServiceStatus.SERVICE_NORMAL_STATUS.getCode()));
                if(0 < syncChargerFeeModelService.save(syncChargerFeeModel)){
                  result = updateFeeModelRel(type,syncChargerFeeModel,stakeNo);
                }
            }
            logger.info("UpdateModelMessageListener_saveModel_FeeModel_save_success_the_id:"+ syncChargerFeeModel.getId());
            //02  服务费模型
        } else if(StakeConsts.FEE_MODEL_TYPE_SERVICE.equals(type)){
            SyncServiceFeeModel syncServiceFeeModel = this.syncServiceFeeModelService.qryServiceFeeModelById(modelId);
            if(syncServiceFeeModel != null){
                logger.info("UpdateModelMessageListener_saveModel_FeeModel_exist:"+JSONObject.toJSONString(item));
            }else{
                syncServiceFeeModel.setId(modelId);
                if(date != null){
                    syncServiceFeeModel.setUneeffectiveat(date);
                }
                syncServiceFeeModel.setEffectiveat( item.getEffectDate());
                //尖峰费率之尖峰率
                syncServiceFeeModel.setSharpfee( item.getPriceSpot().intValueExact());
                //尖峰费率之峰费率
                syncServiceFeeModel.setOvershootfee(item.getPricePeak().intValueExact());
                //平谷费率之平费率
                syncServiceFeeModel.setFlatfee(item.getPricePeace().intValue());
                //平谷费率之谷费率
                syncServiceFeeModel.setValleyfee(item.getPriceVally().intValue());
                //模型名称
                syncServiceFeeModel.setName(item.getModelName());
                syncServiceFeeModel.setStatus(Integer.valueOf(DatabaseServiceStatus.SERVICE_NORMAL_STATUS.getCode()));
                if (0 < syncServiceFeeModelService.save(syncServiceFeeModel)){
                    result = updateFeeModelRel(type,syncServiceFeeModel,stakeNo);
                }
            }
            logger.info("UpdateModelMessageListener_saveModel_FeeModel_save_success_the_id:"+ syncServiceFeeModel.getId());
            return result;
        } else {
            logger.info("UpdateModelMessageListener_saveModel_the_type_of_FeeModel_not_exit:" + JSON.toJSONString(item));
            return result;
        }
        return result;
    }

        /**
         * 更新桩上绑定的计费模型
         * @param type
         * @param obj
         * @param stakeNo
         */
    private int updateFeeModelRel(String type,Object obj,String stakeNo){
        int result = 0;
        String modelid ="";
        BaseFeeModelRel param = new BaseFeeModelRel();
        BaseStake baseStake = this.baseStakeService.getStakeByStakeNo(stakeNo);
        if(baseStake == null){
            logger.info("UpdateModelMessageListener_updateStakeModel_stake_is_null_stakeNo:" + stakeNo);
            return result;
        }
        //计费模型
        if(StakeConsts.FEE_MODEL_TYPE_CHARGER.equals(type)){
            SyncChargerFeeModel syncChargerFeeModel = (SyncChargerFeeModel)obj;
            modelid = syncChargerFeeModel.getId();
            param.setStakeno(stakeNo);
            param.setFeetype(2);
        //服务费模型
        } else if(StakeConsts.FEE_MODEL_TYPE_SERVICE.equals(type)){
            SyncServiceFeeModel syncServiceFeeModel = (SyncServiceFeeModel)obj;
            modelid = syncServiceFeeModel.getId();
            param.setStakeno(stakeNo);
            param.setFeetype(1);
        }
        BaseFeeModelRel baseFeeModelRel = this.baseFeeModelRelService.selectOne(param);
        if(baseFeeModelRel == null){
            logger.error("UpdateModelMessageListener_updateStakeModel_stakeFeeModel_update_error_stakeNo:" + stakeNo);
            return result;
        }
        param.setModeid(modelid);
        param.setUuid(baseFeeModelRel.getUuid());

        result=  this.baseFeeModelRelService.updateByPrimaryKeySelective(param);
        logger.info("UpdateModelMessageListener_updateStakeModel_update_stakeFeeModel_success");

        return result;
    }
}
